﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;

namespace Toybox.SCM.Models.Accounts
{
	using Logger;
	using NicoSharp.Utilities;

	/// <summary>
	/// Accounts
	/// </summary>
	public class AccountCollection : ObservableCollection<Account>
	{

		#region [Static]

		/// <summary>
		/// Load Accounts
		/// </summary>
		/// <param name="filePath"></param>
		/// <returns></returns>
		public static AccountCollection Load(string filePath)
		{
			var accounts = new AccountCollection();

			try
			{
				using (var fs = new FileStream(filePath, FileMode.Open))
				using (var sr = new StreamReader(fs, Encoding.Unicode))
				{
					var elements = CsvUtility.Parse(sr.ReadToEnd());
					foreach (var element in elements)
					{
						accounts.Add(new Account(element));
					}
				}
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
			}

			return accounts;
		}

		/// <summary>
		/// Save Accounts
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="accounts"></param>
		public static void Save(string filePath, AccountCollection accounts)
		{
			try
			{
				using (var fs = new FileStream(filePath, FileMode.Create))
				using (var sw = new StreamWriter(fs, Encoding.Unicode))
				{
					foreach (var account in accounts)
					{
						sw.Write(account.ToString());
					}
				}
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
			}
		}

		#endregion [Static]

	}
}
